#include <Core.h>
#include "ShakeGun.h"
#include "MouseHandle.h"
#include "KeyboardHandle.h"

namespace ShakeGun
{
    bool shake_switch{false};
    bool control_switch{true};
    bool mouse_l_button{false};
    bool mouse_r_button{false};
    HANDLE shake_signal{nullptr};
    bool event_state{false};
    unsigned int mouse_proc_id{0xffff'ffffu};
    unsigned int key_proc_id{0xffff'ffffu};
}

void ShakeGun::open()
{
    shake_switch = true;
    control_switch = true;
    shake_signal = CreateEventW(nullptr,TRUE,FALSE,nullptr);
    mouse_proc_id = MouseHandle::add_proc([](WPARAM w,MSLLHOOKSTRUCT*){

        switch(w)
        {
            case WM_LBUTTONDOWN:
                mouse_l_button = true;
                break;
            case WM_LBUTTONUP:
                mouse_l_button = false;
                break;
            case WM_RBUTTONDOWN:
                mouse_r_button = true;
                break;
            case WM_RBUTTONUP:
                mouse_r_button = false;
                break;
        }

        if(!control_switch){
            return;
        }

        if(mouse_l_button && mouse_r_button && !event_state){
            event_state = true;
            SetEvent(shake_signal);
            INFO("Begin Shake Gun");
        }

        if(!(mouse_l_button && mouse_r_button) && event_state){
            event_state = false;
            ResetEvent(shake_signal);
            INFO("End Shake Gun");
        }

    });

    std::thread([](){
        while(shake_switch){
            WaitForSingleObject(shake_signal,INFINITE);
            mouse_event(MOUSEEVENTF_MOVE,3,2,0,0);
            std::this_thread::sleep_for(std::chrono::milliseconds(25));
            mouse_event(MOUSEEVENTF_MOVE,-3,-2,0,0);
            std::this_thread::sleep_for(std::chrono::milliseconds(25));
        }
    }).detach();

}

void ShakeGun::close()
{
    shake_switch = false;
    CloseHandle(shake_signal);
    MouseHandle::remove_proc(mouse_proc_id);
    KeyboardHandle::remove_proc(key_proc_id);
}
